import aiomysql
from aiomysql import DictCursor
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, status

# 全局连接池对象
pool = None

# 数据库配置（注意将'database'改为'db'）
DB_CONFIG = {
    "host": "obmt6ptq09hrp8xs-mi.aliyun-cn-beijing-internet.oceanbase.cloud",
    "port": 3306,
    "user": "justinc",
    "password": "SJCsjc0315",
    "db": "medicine",  # 注意这里改为'db'而不是'database'
    "autocommit": True,  # 自动提交事务
    "minsize": 3,
    "maxsize": 10
}


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理 - 创建和关闭连接池"""
    global pool
    # 创建连接池
    pool = await aiomysql.create_pool(**DB_CONFIG)
    yield
    # 关闭连接池
    pool.close()
    await pool.wait_closed()


app = FastAPI(lifespan=lifespan)


@asynccontextmanager
async def get_db_cursor():
    """异步上下文管理器获取数据库游标"""
    # 从连接池获取连接
    conn = await pool.acquire()
    try:
        # 创建字典游标
        async with conn.cursor(DictCursor) as cursor:
            try:
                yield cursor
                # 自动提交（除非在事务中手动控制）
                await conn.commit()
            except Exception as e:
                # 出错时回滚
                await conn.rollback()
                raise e
    finally:
        # 释放连接回连接池
        pool.release(conn)
